package com.thenie.chat.controller;

import cn.hutool.core.util.ObjectUtil;
import com.thenie.chat.pojo.User;
import com.thenie.chat.service.impl.RandomChatServiceImpl;
import com.thenie.chat.validator.CurrentUser;
import com.thenie.chat.vo.RespBean;
import com.thenie.chat.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * 随机匹配 控制器
 *
 * @author nieshiji
 * @date 2022/7/27 14:05
 */
@Controller
@RequestMapping("/randomChat")
@Slf4j
public class RandomChatController {

    @Autowired
    private RandomChatServiceImpl randomChatService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @ResponseBody
    @PostMapping("/match")
    public RespBean match(@CurrentUser User curUser) {

        if (DialogRandomSocketHandler.RANDOM_SESSION_MAP.containsKey(String.valueOf(curUser.getId()))){
            return RespBean.success(RespBeanEnum.UPDATE_USER_ERROR,"同一时间段内只能打开一个【机遇之都】窗口哦！");
        }

        try {
            randomChatService.putRequestQueue(curUser);
        } catch (InterruptedException e) {
            return RespBean.error(RespBeanEnum.ERROR);
        }

        return RespBean.success("匹配中...");
    }

    @GetMapping("/random-window/{uid}")
    public String randomWindow(Model model, @PathVariable String uid,@CurrentUser User user) {
        log.info("randomWindow.begin,username:{}",user);

        if (DialogRandomSocketHandler.RANDOM_SESSION_MAP.containsKey(String.valueOf(user.getId()))){
            model.addAttribute("warn", "不可以同时进入多个【机遇之都】界面哦~");
            return "error/error-window";
        }

        String[] userKeys = uid.split("-");
        if (userKeys.length == 2) {
            User my = (User)redisTemplate.opsForValue().get(RandomChatServiceImpl.RANDOM_USER_PREFIX + userKeys[0]);
            User to = (User)redisTemplate.opsForValue().get(RandomChatServiceImpl.RANDOM_USER_PREFIX + userKeys[1]);
            if (ObjectUtil.isAllNotEmpty(my, to) && user.getId().equals(my.getId())) {
                //跳转正确页面
                model.addAttribute("user", my);
                model.addAttribute("toUser", to);

                return "random-window";
            }
        }
        //错误
        model.addAttribute("warn", "随机匹配秘钥不正确~");
        return "error/error-window";
    }

}
